package org.jeecg.modules.assets.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.assets.dto.AssetsApplyDTO;
import org.jeecg.modules.assets.dto.AssetsItemBeachEditDTO;
import org.jeecg.modules.assets.entity.*;
import org.jeecg.modules.assets.mapper.AssetsItemHistoryMapper;
import org.jeecg.modules.assets.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;

import org.jeecg.modules.assets.vo.ItemVO;
import org.jeecg.modules.system.mapper.SysDictItemMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 资产明细
 * @Author: jeecg-boot
 * @Date: 2023-12-12
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "资产明细")
@RestController
@RequestMapping("/assets/assetsItem")
public class AssetsItemController extends JeecgController<AssetsItem, IAssetsItemService> {
    @Autowired
    private IAssetsItemService assetsItemService;

    @Autowired
    private SysDictItemMapper sysDictItemMapper;
    @Autowired
    private IAssetsCategoryService assetsCategoryService;


    /**
     * 分页列表查询
     *
     * @param assetsItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "资产明细-分页列表查询")
    @ApiOperation(value = "资产明细-分页列表查询", notes = "资产明细-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AssetsItem assetsItem, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, @RequestParam(name = "type", defaultValue = "1") String type, HttpServletRequest req) {
        //新增判空
        String assetName = assetsItem.getAssetName();
        String assetCoding = assetsItem.getAssetCoding();
        String deviceCode = assetsItem.getDeviceCode();
        assetsItem.setAssetName(null);
        assetsItem.setAssetCoding(null);
        assetsItem.setDeviceCode(null);
        QueryWrapper<AssetsItem> queryWrapper = QueryGenerator.initQueryWrapper(assetsItem, req.getParameterMap());
        if (StringUtils.isNotEmpty(assetName) && !assetName.equals("null")) {
            if ("1".equals(type)) {
                queryWrapper.eq("asset_name", assetName);
            } else {
                queryWrapper.like("asset_name", assetName);
            }

        }
        if (StringUtils.isNotEmpty(assetCoding) && !assetCoding.equals("null")) {
            queryWrapper.like("asset_coding", assetCoding);
        }
        if (StringUtils.isNotEmpty(deviceCode) && !deviceCode.equals("null")) {
            queryWrapper.like("device_code", deviceCode);
        }

        Page<AssetsItem> page = new Page<AssetsItem>(pageNo, pageSize);
        IPage<AssetsItem> pageList = assetsItemService.page(page, queryWrapper);
        for (AssetsItem record : pageList.getRecords()) {
            //判断分类
            if (record.getCategory() != null) {
                AssetsCategory byId = assetsCategoryService.getById(record.getCategory());
                if (byId != null) {
                    record.setAssetCoding(byId.getAlias() != null ? byId.getAlias() + record.getAssetCoding() : record.getAssetCoding());
                }
            }
        }
        return Result.OK(pageList);
    }


    /**
     * 分页列表查询
     *
     * @param assetsItem
     * @param pageNo
     * @param pageSize   再借设备
     * @param req
     * @return
     */
    @AutoLog(value = "资产明细-外借资产分页列表查询")
    @ApiOperation(value = "资产明细-外借资产分页列表查询", notes = "资产明细-外借资产 分页列表查询")
    @GetMapping(value = "/queryPageListByApply")
    public Result<?> queryPageListByApply(AssetsApplyDTO assetsItem, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<AssetsApplyDTO> page = new Page<AssetsApplyDTO>(pageNo, pageSize);
        IPage<AssetsApplyDTO> pageList = assetsItemService.queryPageListByApply(page, assetsItem);
        for (AssetsApplyDTO record : pageList.getRecords()) {
            //判断分类
            if (record.getCategory() != null) {
                AssetsCategory byId = assetsCategoryService.getById(record.getCategory());
                if (byId != null) {
                    assetsItem.setAssetCoding(byId.getAlias() != null ? byId.getAlias() + assetsItem.getAssetCoding() : assetsItem.getAssetCoding());
                }
            }
        }
        return Result.OK(pageList);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param assetsItem
     */
    @PostMapping(value = "/exportXlsApply")
    @ApiOperation("借出资产导出")
    public ModelAndView exportXlsApply(@RequestBody AssetsApplyDTO assetsItem) {
        return assetsItemService.exportXlsApply(assetsItem, AssetsApplyDTO.class, "在借设备");
    }


    /**
     * 分页列表查询
     *
     * @param assetsItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "资产明细-分页列表查询")
    @ApiOperation(value = "资产明细-分页列表查询", notes = "资产明细-分页列表查询")
    @GetMapping(value = "/listall")
    public Result<?> listall(AssetsItem assetsItem, HttpServletRequest req) {
        int pageSize = 100000000;
        int pageNo = 1;
        //默认过滤掉已申领的
        if (StringUtils.isNotEmpty(assetsItem.getAssetName())) {
            assetsItem.setAssetName("*" + assetsItem.getAssetName() + "*");
        }
        assetsItem.setApplyStatus(1);
        QueryWrapper<AssetsItem> queryWrapper = QueryGenerator.initQueryWrapper(assetsItem, req.getParameterMap());
        Page<AssetsItem> page = new Page<AssetsItem>(pageNo, pageSize);
        IPage<AssetsItem> pageList = assetsItemService.page(page, queryWrapper);
        return Result.OK(pageList.getRecords());
    }


    /**
     * 分页列表查询
     *
     * @param assetsItem
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "资产明细-分页列表查询")
    @ApiOperation(value = "资产明细-分页列表查询", notes = "资产明细-分页列表查询")
    @GetMapping(value = "/listallwaitReturn")
    public Result<?> listallwaitReturn(AssetsItem assetsItem, HttpServletRequest req) {
        int pageSize = 100000000;
        int pageNo = 1;
        //默认过滤掉已申领的
        if (StringUtils.isNotEmpty(assetsItem.getAssetName())) {
            assetsItem.setAssetName("*" + assetsItem.getAssetName() + "*");
        }
        assetsItem.setApplyStatus(0);
        QueryWrapper<AssetsItem> queryWrapper = QueryGenerator.initQueryWrapper(assetsItem, req.getParameterMap());
        Page<AssetsItem> page = new Page<AssetsItem>(pageNo, pageSize);
        IPage<AssetsItem> pageList = assetsItemService.page(page, queryWrapper);
        return Result.OK(pageList.getRecords());
    }


    @AutoLog(value = "资产明细-分页列表查询,绑定设备明细")
    @ApiOperation(value = "资产明细-，分页列表查询，绑定设备明细", notes = "资产明细-绑定设备明细")
    @GetMapping(value = "/listByBind")
    public Result<?> queryPageListByBind(AssetsItem assetsItem, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        QueryWrapper<AssetsItem> queryWrapper = new QueryWrapper<>();
        if (Objects.equals(assetsItem.getQueryType(), "1")) {
            queryWrapper.isNull("category");
        } else {
            queryWrapper.isNull("group_name");
        }
        assetsItem.setQueryType(null);
        if (StringUtils.isNotEmpty(assetsItem.getAssetName())) {
            queryWrapper.like("asset_name", assetsItem.getAssetName());
        }
        Page<AssetsItem> page = new Page<AssetsItem>(pageNo, pageSize);
        IPage<AssetsItem> pageList = assetsItemService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 添加
     *
     * @param assetsItem
     * @return
     */
    @AutoLog(value = "资产明细-添加")
    @ApiOperation(value = "资产明细-添加", notes = "资产明细-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AssetsItem assetsItem) {
        assetsItemService.saveItem(assetsItem);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param assetsItem
     * @return
     */
    @AutoLog(value = "资产明细-编辑")
    @ApiOperation(value = "资产明细-编辑", notes = "资产明细-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> edit(@RequestBody AssetsItem assetsItem) {
        assetsItemService.editItem(assetsItem);
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param assetsItem
     * @return
     */
    @AutoLog(value = "资产明细-绑定或解绑分类")
    @ApiOperation(value = "资产明细-绑定或解绑分类", notes = "资产明细-编辑")
    @RequestMapping(value = "/bingCatagery", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> bingCatagery(@RequestBody AssetsItem assetsItem) {
        assetsItemService.bingCatagery(assetsItem);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "资产明细-绑定或解绑编组")
    @ApiOperation(value = "资产明细-绑定或解绑编组", notes = "资产明细-编辑")
    @RequestMapping(value = "/bingGroup", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> bingGroup(@RequestBody AssetsItem assetsItem) {
        assetsItemService.bingGroup(assetsItem);
        return Result.OK("编辑成功!");
    }

    /**
     * 批量编辑
     *
     * @param assetsItemList
     * @return
     */
    @AutoLog(value = "资产明细-批量编辑")
    @ApiOperation(value = "资产明细-批量编辑", notes = "资产明细-批量编辑")
    @RequestMapping(value = "/editBatch", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> batch(@RequestBody List<AssetsItem> assetsItemList) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String realname = loginUser.getRealname();
        List<String> tenantIds = sysDictItemMapper.getTenantId(realname);
        for (AssetsItem assetsItem : assetsItemList) {
            String companyId = assetsItem.getCompany();
            Integer companyIdInt = Integer.parseInt(companyId);
            if (tenantIds.contains(companyIdInt)) {
                assetsItemService.editItem(assetsItem);
            } else {
                return Result.error("当前登录用户不允许修改");
            }
        }
        return Result.OK("批量编辑成功!");
    }


    /**
     * 批量编辑
     *
     * @param assetsItemList
     * @return
     */
    @AutoLog(value = "资产明细-批量编辑状态编辑")
    @ApiOperation(value = "资产明细-批量编辑状态编辑", notes = "资产明细-批量编辑状态编辑")
    @RequestMapping(value = "/editBatchStatus", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> editBatchStatus(@RequestBody AssetsItem assetsItem) {

        assetsItemService.editBatchStatus(assetsItem);


        return Result.OK("批量编辑成功!");
    }


    /**
     * 批量编辑
     *
     * @param assetsItemList
     * @return
     */
    @AutoLog(value = "资产明细-批量编辑备注编辑")
    @ApiOperation(value = "资产明细-批量编辑备注编辑", notes = "资产明批量编辑状态编辑细-批量编辑备注编辑")
    @RequestMapping(value = "/editBatchRemark", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<?> editBatchRemark(@RequestBody AssetsItemBeachEditDTO assetsItem) {
        for (String id : assetsItem.getIds().split(",")) {
            AssetsItem assetsItem1 = new AssetsItem();
            assetsItem1.setId(TypeUtils.castToInt(id));
            assetsItem1.setRemark(assetsItem.getRemark());
            assetsItemService.editBatchRemark(assetsItem1);

        }
        return Result.OK("批量编辑成功!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "资产明细-通过id删除")
    @ApiOperation(value = "资产明细-通过id删除", notes = "资产明细-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        assetsItemService.deletItem(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     * 2
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "资产明细-批量删除")
    @ApiOperation(value = "资产明细-批量删除", notes = "资产明细-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        for (String s : ids.split(",")) {
            assetsItemService.deletItem(s);
        }
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "资产明细-通过id查询")
    @ApiOperation(value = "资产明细-通过id查询", notes = "资产明细-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        //取后六位

        if (StringUtils.isNotEmpty(id)) {
            id = id.substring(id.length() - 6);
        }
        AssetsItem assetsItem = assetsItemService.queryById(id);
        return Result.OK(assetsItem);
    }


    /**
     * 导出excel
     *
     * @param request
     * @param assetsItem
     */
    /**
     * 导出excel
     *
     * @param request
     * @param assetsManger
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, @RequestBody AssetsItem assetsItem) {
        String title = "设备信息明细";
        if("1".equals(assetsItem.getExcType())){
            title="设备信息分组";
        }
        return super.exportXls(request, assetsItem, AssetsItem.class, title);
    }

    /*
     */
/**
 * 通过excel导入数据
 *
 * @param request
 * @param response
 * @return
 *//*

    @ApiOperation("资产明细导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        String msg = assetsItemService.importExcel(request, response);
        return Result.OK(msg);
    }
*/


    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AssetsItem.class);
    }

    /**
     * 下载模板
     */
    @ApiOperation("模版下载")
    @RequestMapping(value = "/downloadTemplate")
    public void downloadTemplate(@RequestParam("type") String type, HttpServletResponse response) {
        String path = this.getClass().getResource("/").getPath();
        switch (type) {
            case "1":
                //返回导入模版
                //获取资源路径
                path += "设备导入模版.xls";
                break;

            case "2":
                //返回申领模版
                path += "设备导入模版.xls";
                break;
            default:
                return;
        }
        File file = new File(path);
        //获取输出流
        response.setContentType(ContentType.DEFAULT_BINARY.getMimeType());
        String name = new String(file.getName().getBytes());
        response.addHeader("Content-Disposition", "attachment;fileName=" + name);
        response.addHeader("Content-Length", "" + file.length());
        try {
            response.getOutputStream().write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
